package reign.network.client;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import reign.engine.Message;
import reign.engine.Message.messageType;
import reign.engine.exceptions.ConnectionReconnectedException;
import reign.engine.exceptions.RecievedNonMessageException;
import reign.network.client.Session;

public class MessageHandlerClient extends Thread{
	
		private boolean stop;
		private Session users;
		private HashMap<messageType,ArrayList<MessageListener>> _listeners;
	
		public MessageHandlerClient(Session HandleMe)
		{
			users = HandleMe;
			_listeners = new HashMap<messageType,ArrayList<MessageListener>>();
			_listeners.put(messageType.CHAT, new ArrayList<MessageListener>());
			_listeners.put(messageType.EVENT, new ArrayList<MessageListener>());
			_listeners.put(messageType.NOTIFICATION, new ArrayList<MessageListener>());
			_listeners.put(messageType.PRIORITY, new ArrayList<MessageListener>());
			_listeners.put(messageType.REQUEST, new ArrayList<MessageListener>());
			
		}
		
		
		public void addListener(messageType type, MessageListener me)
		{
			_listeners.get(type).add(me);
		}
		
		public void fireEvent(messageType type,Message fireMe)
		{
			MessageListener [] itemsListening = _listeners.get(type).toArray(new MessageListener[1]);
			for(int i = 0; i < itemsListening.length;i++)
			{
				itemsListening[i].catchEvent(fireMe);
			}
		}
		
		public void start()
		{
			super.start();
			stop = false;
		}
		
		public void stopSession()
		{
			if(this.isAlive())
			{
				stop = true;
			}
		}
		
		public void run()
		{
			while(!stop)
			{
					try {
						Message incoming = users.getMessage();
						fireEvent(incoming.getType(),incoming);
					} catch (IOException e) {
						System.err.println(e.getMessage());
						this.stopSession();
					} catch (ConnectionReconnectedException e) {
					} catch (RecievedNonMessageException e) {
					}
			}
		}


}
